package com.qining618.cms.cms.service.impl;

import com.qining618.cms.cms.domain.ContentCount;
import com.qining618.cms.cms.enums.ContentOperateEnum;
import com.qining618.cms.cms.mapper.ContentCountMapper;
import com.qining618.cms.cms.service.ContentCountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qining618.cms.cms.service.ContentRecordService;
import com.qining618.common.exception.BusinessException;
import com.qining618.common.result.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * CMS内容计数表 服务实现类
 * </p>
 *
 * @author qining
 * @date 2019-09-17
 */
@Transactional(readOnly = true, rollbackFor = Exception.class)
@Service
public class ContentCountServiceImpl extends ServiceImpl<ContentCountMapper, ContentCount> implements ContentCountService {

    @Autowired
    private ContentRecordService contentRecordService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void incCommentCount(Long contentId) {
        // 增加内容评论点赞数
        int opNum = this.baseMapper.incCommentCount(contentId, 1);
        if (opNum != 1) {
            throw new BusinessException(ErrorCode.DB_ERROR);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int contentUp(Long contentId, Long userId) {
        // 是否重复顶
        boolean isExist = this.contentRecordService.hasContentUp(contentId, userId);
        if (isExist) {
            throw new BusinessException(ErrorCode.DATA_CONFLICT, "请勿重复顶");
        }

        // 增加内容顶数
        int opNum = this.baseMapper.incContentUp(contentId, 1);
        if (opNum != 1) {
            throw new BusinessException(ErrorCode.DB_ERROR);
        }

        // 保存操作记录
        this.contentRecordService.save(contentId, userId, ContentOperateEnum.UP);

        // 获取内容顶数
        return this.baseMapper.getContentUpsByContentId(contentId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int contentDown(Long contentId, Long userId) {
        // 是否重复踩
        boolean isExist = this.contentRecordService.hasContentDown(contentId, userId);
        if (isExist) {
            throw new BusinessException(ErrorCode.DATA_CONFLICT, "请勿重复踩");
        }
        // 增加内容踩数
        int opNum = this.baseMapper.incContentDown(contentId, 1);
        if (opNum != 1) {
            throw new BusinessException(ErrorCode.DB_ERROR);
        }

        // 保存操作记录
        this.contentRecordService.save(contentId, userId, ContentOperateEnum.DOWN);

        // 获取内容踩数
        return this.baseMapper.getContentDownsByContentId(contentId);
    }
}
